package com.xjj.service.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjj.entity.AdviceCatogery;
import com.xjj.service.exception.VertifyException;
import com.xjj.service.mapper.AdviceCategoryMapper;
import com.xjj.service.service.AdviceCategoryService;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description 通知类型
 * @Author zhangjin
 * @Date 2022/10/20 10:07
 */
@Service
public class AdviceCategoryImpl extends ServiceImpl<AdviceCategoryMapper, AdviceCatogery> implements AdviceCategoryService {

    private final String ADVICE_TYPE="catogery:type";
    @Autowired
    private AdviceCategoryMapper mapper;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 查询所有通知类别，存入缓存
     * @return
     */
    @Override
    public List<AdviceCatogery> getCatogeryList() {
        Object o = redisTemplate.opsForValue().get(ADVICE_TYPE);
        // 判断缓存是否存在，不存在---> 查数据库并加入缓存，存在--->直接返回
        if (o!=null){
            return (List<AdviceCatogery>) o;
        }else{
            List<AdviceCatogery> list= mapper.selectList(null);
            redisTemplate.opsForValue().set(ADVICE_TYPE,list);
            return list;
        }
    }

    @Override
    public void delCatogery(int id){
        // 先删除缓存，在删数据库
        redisTemplate.delete(ADVICE_TYPE);
        mapper.deleteById(id);
    }

    @Override
    public void addCatogery(AdviceCatogery catogery) {
        List<AdviceCatogery> catogeryList = mapper.selectList(null);
        long count = catogeryList.stream().filter(e -> catogery.getName().equals(e.getName())).count();
        if (count > 0){
            throw new VertifyException("通知类别已存在");
        }
        if (StringUtil.isNullOrEmpty(catogery.getName())){
            throw new VertifyException("通知类别不能为空");
        }
        // 先删除缓存，再更新数据库
        redisTemplate.delete(ADVICE_TYPE);
        mapper.insert(catogery);
    }

    @Override
    public void updateCatogery(AdviceCatogery catogery) {
        List<AdviceCatogery> catogeryList = mapper.selectList(null);
        long count = catogeryList.stream().filter(e -> catogery.getName().equals(e.getName())).count();
        if (count > 0){
            throw new VertifyException("通知类别已存在");
        }
        if (StringUtil.isNullOrEmpty(catogery.getName())){
            throw new VertifyException("通知类别必须存在");
        }
        // 先删除缓存，再更新数据库
        redisTemplate.delete(ADVICE_TYPE);
        mapper.updateById(catogery);
    }

}
